package ae.pcfc.cldos.online.web.controller.client.company.nocandletters;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import ae.pcfc.cldos.online.common.ConstantsCommon;
import ae.pcfc.cldos.online.common.UltimusConstants.AdminDecision;
import ae.pcfc.cldos.online.common.delegate.CompanyAdminDelegate;
import ae.pcfc.cldos.online.common.exception.BadAppException;
import ae.pcfc.cldos.online.common.exception.LeaseExpireException;
import ae.pcfc.cldos.online.common.exception.LicenseErrorRemarkException;
import ae.pcfc.cldos.online.common.exception.LicenseExpiredException;
import ae.pcfc.cldos.online.common.exception.PaymentException;
import ae.pcfc.cldos.online.common.exception.UltimusAppException;
import ae.pcfc.cldos.online.common.vo.AdminDecisionVO;
import ae.pcfc.cldos.online.common.vo.AppSaveResponseVO;
import ae.pcfc.cldos.online.common.vo.nandl.NocLetterVO;
import ae.pcfc.cldos.online.web.Constants;
import ae.pcfc.cldos.online.web.PageType;
import ae.pcfc.cldos.online.web.ViewPath;
import ae.pcfc.cldos.online.web.ViewUtils;
import ae.pcfc.cldos.online.web.model.NocAndLettersModel;
import ae.pcfc.cldos.online.web.services.breadcrumbs.BreadCrumbsFactoryService;

/**
 * 
 * @author Sergey Manoylo
 *
 */
@Controller
@RequestMapping(ViewPath.__NOC_LETTERS_MAINADMIN)
public class NocAndLettersMainadminController extends NocAndLettersCommonController {
	
	private static final String NOC_AND_LETTERS_PATH = "client.company.nocandletters.mainadmin.form";
	
	@Autowired
	@Qualifier("companyAdminDelegate")
	private CompanyAdminDelegate companyAdminDelegate;	
	
	@ModelAttribute
	public void populateBreadCrumbs(ModelMap model, @RequestParam String appId) {
		breadCrumbsFactoryService.populateNocAndLettersTasktBreadcrumb(model, appId, BreadCrumbsFactoryService.TASK_TYPE_MAIN_ADMIN_APPROVE);
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/form.htm")
	public ModelAndView form( HttpServletRequest request,
			ModelMap model,
			@RequestParam String appId,			
			@ModelAttribute(value="nocAndLettersModel") NocAndLettersModel nocAndLettersModel,
			BindingResult errors) throws BadAppException {
		
		NocLetterVO nocLetterVO = getNocLetterDelegate().getNocLetterAppInfo(encryptionDelegate.decodeAndDecrypt(appId), getUserVO(), ConstantsCommon.Steps.MAIN_ADMIN_APPROVE);
		getMapper().map(nocLetterVO.getNocLetterDetailsVO(),nocAndLettersModel);
		
		model.put("appId", appId);
		model.put("nocAndLettersModel",nocAndLettersModel);
		model.put("comments", nocLetterVO.getApplicationCommentVOs());		
		
		return new ModelAndView(NOC_AND_LETTERS_PATH,model);
	}
	
	@RequestMapping(method=RequestMethod.POST, value="/form.htm")
	public ModelAndView submit(
			HttpServletRequest request,
			ModelMap model,
			@RequestParam(required=false, defaultValue="false") boolean isResubmit,
			@RequestParam(required=false) 	String fnpServiceCode,	
			@RequestParam(required=false) 	String formId,
			@RequestParam(required=true) 	String appId,	
			@RequestParam(required=false) 	String adminComments,			
			@ModelAttribute(value="nocAndLettersModel") NocAndLettersModel nocAndLettersModel,
			BindingResult errors
			) throws Exception {
		
		boolean isSubmitApproval = WebUtils.hasSubmitParameter(request, "MainUserApprove");
		boolean isSubmitReject = WebUtils.hasSubmitParameter(request, "MainUserReject");
		boolean isSubmitCancel = WebUtils.hasSubmitParameter(request, "MainUserCancel");
		Map<String, String> paramMap = new HashMap<String, String>();
		
		AdminDecisionVO adminDecisionVO = new AdminDecisionVO();
		
		if(isSubmitApproval){
			processFnp(request,fnpServiceCode,errors,adminDecisionVO.getFnpParamsVO());			
		} else if(isSubmitReject){
			if(adminComments==null || adminComments.isEmpty()){
				errors.reject("admin.comment.required");
			}
			adminDecisionVO.setStrActionType(AdminDecision.REJECTED.getAdminDecision());
		}
		
		adminDecisionVO.setApplicationId(encryptionDelegate.decodeAndDecrypt(appId));
		adminDecisionVO.setUserVO(getUserVO());
		adminDecisionVO.setFnpServiceCode(fnpServiceCode);
		adminDecisionVO.setComment(adminComments);		
		
		if(isSubmitApproval){
			adminDecisionVO.setStrActionType(AdminDecision.APPROVED.getAdminDecision());
		} else if(isSubmitReject) {
			adminDecisionVO.setStrActionType(AdminDecision.REJECTED.getAdminDecision());
		} else if(isSubmitCancel){
			adminDecisionVO.setStrActionType(AdminDecision.CANCELLED.getAdminDecision());
		}
		
		if(!errors.hasErrors()){
			try{
				AppSaveResponseVO appSaveResponseVO = companyAdminDelegate.companyAdminAction(adminDecisionVO);
				paramMap.put(Constants.__REFRENCE_NO, appSaveResponseVO.getReferenceNo());
				paramMap.put(Constants.__INCIDENT_NO, appSaveResponseVO.getIncidentNo());
			} catch (PaymentException e) {
				errors.reject("error.payment");
			} catch (LeaseExpireException e){
				errors.reject("lease.expire");
			} catch (LicenseExpiredException e) {
				errors.reject("license.expire");
			}catch (LicenseErrorRemarkException e) {
				errors.reject("license.errorremark");
			}catch(UltimusAppException e){
				e.printStackTrace();
				errors.reject("unable.to.proceed.ultimus.down");
			}catch(Exception e){
				e.printStackTrace();
				errors.reject("unable.to.proceed");
			}
		}
		
		if(!errors.hasErrors()){
			return new ModelAndView(ViewUtils.getRedirect(ViewPath.__CONFIRMATION, PageType.SHOW, paramMap));
		} else {
			return form(request, model, appId, nocAndLettersModel, errors);
		}
	}


}
